<?php 
// Force the browser to use no cache
//header ("Cache-Control: no-cache, must-revalidate");              // HTTP/1.1
//header ("Pragma: no-cache");                                      // HTTP/1.0

// this feed is passed to the web app
$feed = "http://www.google.com/calendar/feeds/" . $_GET['url'] . "/public/full?orderby=starttime&singleevents=true&max-results=1000";

$doc = new DOMDocument(); 
$doc->load($feed);
$entries = $doc->getElementsByTagName("entry"); 
$calTitle = $doc->getElementsByTagName("title")->item(0)->nodeValue;

$xml_events_file;

$url = $_GET['url'];

function addToDatabase($_title, $_url){
	$newEntry = "{\"name\":\"" . $_title . "\", \"url\":\"" . $_url . "\"},";
	$database = "database.js";
	$content = file_get_contents($database); 
	file_put_contents($database, substr($content, 0, strrpos($content,"\n")) . "\n" . $newEntry . "\n];");
}

function removeFromDatabase($_title, $_url){
	$oldEntry = "{\"name\":\"" . $_title . "\", \"url\":\"" . $_url . "\"},";
	$file = fopen("database.js", "r");
	$contents = fread($file, filesize("database.js"));
	$updatedContent = str_replace($oldEntry, "", $contents);
	fclose($file);
	$handle = fopen("database.js", 'w');
	fwrite($handle, $updatedContent);
	fclose($handle);
	echo "<script type='text/javascript'>window.location.href='index.php';window.location.self.reload();</script>";
}

function saveXMLFile(){
	$events = 'events.xml';
	$favorite = 'favorites/'. $_GET['url'] .'.xml';
	if (!copy($events, $favorite)) {
	    echo "Failed to copy $events...\n";
	}
}

function createXMLfromGCalendar(){
	// this feed is passed to the web app
	global $feed;
	global $entries;
	
	// Initialization of the on-the-fly xml_events_file called events.xml
	$xmldb = "events.xml";
	$handle = fopen($xmldb, 'w');
	fwrite($handle, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<data>\n</data>");
	
	// Creation on-the-fly of the xml_events_file called events.xml
	// Using the feed obtained by Google an the DOMDocument as a parser
	foreach($entries as $entry) { 
		$titles = $entry->getElementsByTagName("title"); 
		$title = $titles->item(0)->nodeValue;

		$times = $entry->getElementsByTagName("when"); 
		$startTime = $times->item(0)->getAttributeNode("startTime")->value;
		$endTime = $times->item(0)->getAttributeNode("endTime")->value;

		$whenStarts = date( "D M j Y G:i", strtotime($startTime));
		$whenEnds = date( "D M j Y G:i", strtotime($endTime));

		$bodies = $entry->getElementsByTagName("content"); 
		$body = $bodies->item(0)->nodeValue;

		$places = $entry->getElementsByTagName("where"); 
		$where = $places->item(0)->getAttributeNode("valueString")->value;

		//Testing the fields
		//print "Title: " . $title . "<br/>"; 
		//print "Starts: " . $whenStarts . "<br/>"; 
		//print "Ends: " . $whenEnds . "<br/>"; 
		//if($where) print "Where: " . $where . "<br/>";
		//if($content) print "Content: " . $content;
		//print "<br/><br/>";

		// Appending each event to the XML database
		$content = file_get_contents($xmldb); 
		//$title = str_replace("&", "&amp;", $title);
		//$body = str_replace("&", "&amp;", $body);
		if(($whenStarts !== $whenEnds) && ($whenEnds != 'Thu Jan 1 1970 1:00'))
			file_put_contents($xmldb, substr($content, 0, strrpos($content,"\n")) . "\n<event start=\"".$whenStarts. " GMT\" end=\"".$whenEnds." GMT\" isDuration=\"true\" title=\"" .  htmlspecialchars(stripslashes($title)) ."\">". htmlspecialchars(stripslashes($body)) ."</event>\n</data>");
		else 
			// Syntax of bullet events is without the end field in the XML database
			file_put_contents($xmldb, substr($content, 0, strrpos($content,"\n")) . "\n<event start=\"".$whenStarts. " GMT\" isDuration=\"true\" title=\"" . htmlspecialchars(stripslashes($title)) ."\">". htmlspecialchars(stripslashes($body)) ."</event>\n</data>");
	}
	global $xml_events_file;
	$xml_events_file = "events.xml";
}

function useExistingXML(){
	global $xml_events_file;
	$xml_events_file = "favorites/" . $_GET['url'] . ".xml";
}

// Gets the feed from Google and update the cashed favorite's XML
if($_GET['update'] == 'true'){
	createXMLfromGCalendar();
	saveXMLFile();
}

if($_GET['favorite'] == 'remove'){
	removeFromDatabase($_GET['title'], $_GET['url']);
}

// Verify wheter we have to fetch from existing file 
// or create on-the-fly a new one.
if($_GET['favorite'] == 'true' && $_GET['update'] !== 'true'){
	useExistingXML();
} else if ($_GET['favorite'] == 'false')
	createXMLfromGCalendar();

// Generating the timeline
include_once("main.php");

// We want to add the current calendar to our favorites
if(isset($_GET['url']) && isset($_GET['title']) && $_GET['favorite'] !== 'remove'){
	//print_r($_GET);
	addToDatabase($_GET['title'], $_GET['url']);
	saveXMLFile();
}
?>